package h0902;

import java.util.Arrays;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 最接近的三数之和
 * @date 2024/9/2 19:37
 */
public class ThreeSum {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4};
        int num = 5;
        System.out.println(threeSumClosest2(nums, num));
    }

    public static int threeSumClosest(int[] nums, int target) {
        int min = Integer.MAX_VALUE;
        int[] ans = new int[3];
        for (int i = 0; i < nums.length; i++) {
            int a = target - nums[i];
            for (int j = i + 1; j < nums.length; j++) {
                for (int k = j + 1; k < nums.length; k++) {
                    if (Math.abs(nums[j] + nums[k] - a) < min) {
                        ans = new int[]{nums[i], nums[j], nums[k]};
                        min = Math.abs(nums[j] + nums[k] - a);
                    }
                }
            }
        }
        return Arrays.stream(ans).sum();
    }

    public static int threeSumClosest2(int[] nums, int target) {
        int min = Integer.MAX_VALUE / 2;
        int[] ans = new int[3];
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int curSum = nums[left] + nums[right] + nums[i];
                if (curSum == target) {
                    return target;
                }
                if (Math.abs(target - curSum) < Math.abs(min - target)) {
                    min = curSum;  //更小的和
                }
                if (curSum > target) {
                    right--;
                } else {
                    left++;
                }
            }
        }
        return min;
    }
}
